package com.zahb.qadx.ui.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseDelegateMultiAdapter;
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.ExaminationListBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.activity.topic.ResultsPageActivity;
import com.zahb.qadx.ui.activity.topic.TheTestActivity;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by Zdw on 2020/11/10 15:00
 * 考试列表
 */
public class ExaminationListFragment extends BaseFragmentExt implements OnRefreshLoadMoreListener {

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;

    private boolean mHasClickToNewPage = false;// 记录点击跳转新页面
    private boolean mIsFirstLoad = true;// 是否第一次，处理懒加载
    private int mPage;
    private static final int PAGE_SIZE = 10;
    private int mType;// 0待完成 1已完成 2未开始 3未完成
    private ExaminationListAdapter mAdapter;

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    private ExaminationListFragment() {
    }


    public static ExaminationListFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        ExaminationListFragment fragment = new ExaminationListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = mArguments.getInt("type", -1);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsFirstLoad) {
            mIsFirstLoad = false;
            //mRefreshLayout.autoRefresh();
            onRefresh(mRefreshLayout);
            showSkeleton();
        }

        if (mHasClickToNewPage) {
            mHasClickToNewPage = false;
            mRefreshLayout.autoRefresh();

        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_examination_list;
    }

    @Override
    protected void initViews(View rootView) {
        mUnbinder = ButterKnife.bind(this, rootView);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new ExaminationListAdapter(mType);
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mAdapter.setEmptyView(emptyView);
        mRecyclerView.setAdapter(mAdapter);
        int dividerHeight = DisplayUtil.dip2px(20f);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                if (parent.getChildAdapterPosition(view) != 0) {
                    outRect.set(0, dividerHeight, 0, 0);
                } else {
                    outRect.set(0, 0, 0, 0);
                }
            }
        });
    }

    private void showSkeleton() {
        mRefreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(mRecyclerView)
                .adapter(mAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_task_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mRefreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    private void getExaminationList() {
        addDisposable(RetrofitService.getNetService()
                .getExaminationList(mPage, PAGE_SIZE, mType)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (mPage == 1) {
                        mRefreshLayout.finishRefresh();
                        if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                            mAdapter.setList(response.getData().getList());
                        }
                    } else {
                        mRefreshLayout.finishLoadMore(1000);
                        if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                            mAdapter.addData(response.getData().getList());
                        }
                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    if (mPage == 1) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        mRefreshLayout.finishLoadMore(1000);
                    }
                    hideSkeleton();
                }));
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPage++;
        getExaminationList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        getExaminationList();
    }

    private class ExaminationListAdapter extends BaseDelegateMultiAdapter<ExaminationListBean, BaseViewHolder> {

        private int mType;// 0待完成 1已完成 2未开始 3未完成

        ExaminationListAdapter(int type) {
            this.mType = type;
            setMultiTypeDelegate(new BaseMultiTypeDelegate<ExaminationListBean>() {
                @Override
                public int getItemType(@NotNull List<? extends ExaminationListBean> list, int i) {
                    return type;
                }
            });
            assert getMultiTypeDelegate() != null;
            getMultiTypeDelegate().addItemType(0, R.layout.item_list_examination_type0);
            getMultiTypeDelegate().addItemType(1, R.layout.item_list_examination_type1);
            getMultiTypeDelegate().addItemType(2, R.layout.item_list_examination_type0);
            getMultiTypeDelegate().addItemType(3, R.layout.item_list_examination_type0);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, ExaminationListBean bean) {
            baseViewHolder.setText(R.id.tv_title, bean.getName())
                    .setText(R.id.tv_start_time, new StringBuilder("开始时间：").append(bean.getStartTime()))
                    .setText(R.id.tv_end_time, new StringBuilder("结束时间：").append(bean.getEndTime()));

            if (mType == 0 || mType == 2 || mType == 3) {
                CardView btnCardView = baseViewHolder.getView(R.id.btn_card_view);
                TextView textView = baseViewHolder.getView(R.id.tv_btn_card_view);
                if (mType == 0) {
                    btnCardView.setCardBackgroundColor(Color.parseColor("#1677FF"));
                    textView.setText(R.string.start_examination);
                    textView.setEnabled(true);
                    textView.setOnClickListener(mOnClickListener);
                    textView.setTag(bean);
                } else if (mType == 2) {
                    btnCardView.setCardBackgroundColor(Color.parseColor("#CED0D3"));
                    textView.setText(R.string.start_examination);
                    textView.setEnabled(false);
                } else if (mType == 3) {
                    btnCardView.setCardBackgroundColor(Color.parseColor("#CED0D3"));
                    textView.setText(R.string.examination_end);
                    textView.setEnabled(false);
                }
            } else if (mType == 1) {
                baseViewHolder.setText(R.id.tv_achievement, new StringBuilder("成绩：").append(bean.getMaxScore()))
                        .setGone(R.id.tv_re_examination, bean.getExamCount() >= bean.getExamTotalCount() && bean.getExamTotalCount() != 0);
                baseViewHolder.getView(R.id.tv_view_achievement).setOnClickListener(mOnClickListener);
                baseViewHolder.getView(R.id.tv_view_achievement).setTag(bean);
                baseViewHolder.getView(R.id.tv_re_examination).setOnClickListener(mOnClickListener);
                baseViewHolder.getView(R.id.tv_re_examination).setTag(bean);
            }
        }
    }

    private View.OnClickListener mOnClickListener = v -> {
        if (v.getId() == R.id.tv_btn_card_view || v.getId() == R.id.tv_re_examination) {// 开始考试，重新考试
            ExaminationListBean bean = (ExaminationListBean) v.getTag();
            if (bean != null) {
                try {
                    String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                    String url = WebViewHelper.getBaseUrl() + "exam/examInfo?sourceId=" + bean.getExamId() + "&fromType=1&token=" + token;
                    Log.e("MyWebViewActivity", "url: " + url);
                    SharedPreferences settingss = getActivity().getSharedPreferences("tryToSwitch", 0);
                    int isAmazing = settingss.getInt("tryToSwitch", 0);

                    if (isAmazing == 2) {
                        //梁尔宾 原生去考试
                        Intent intent = new Intent(getActivity(), TheTestActivity.class);
                        intent.putExtra("examId", bean.getExamId() + "");
                        intent.putExtra("relationshipId", "");
                        startActivity(intent);
                    } else {
                        MyWebViewActivity.actionStart(v.getContext(), url, "", 1);
                    }

                    mHasClickToNewPage = true;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        } else if (v.getId() == R.id.tv_view_achievement) {// 查看成绩
            ExaminationListBean bean = (ExaminationListBean) v.getTag();
            if (bean != null) {
                try {
                    String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                    String url = WebViewHelper.getBaseUrl() + "exam/examResult?sourceId=" + bean.getExamId() + "&resultType=1&fromType=1&token=" + token;
                    Log.e("MyWebViewActivity", "url: " + url);
                    SharedPreferences settingss = getActivity().getSharedPreferences("tryToSwitch", 0);
                    int isAmazing = settingss.getInt("tryToSwitch", 0);
                    if (isAmazing == 2) {
                        Intent intent = new Intent(getActivity(), ResultsPageActivity.class);
                        intent.putExtra("sourceId", bean.getExamId() + "");
                        startActivity(intent);
                    } else {
                        MyWebViewActivity.actionStart(v.getContext(), url, "", 1);
                    }

                    //梁尔宾 原生去考试 查看成绩

                    mHasClickToNewPage = true;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}
